package com.imonsoft.sqm.validator.sys;

import com.imonsoft.sqm.pojo.sys.Role;
import com.imonsoft.sqm.service.MessageUtil;
import com.imonsoft.sqm.service.sys.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.*;

import java.util.ArrayList;
import java.util.List;

@Component("roleValidator")
public class RoleValidator implements Validator {

	@Autowired
	private RoleService roleService;
	@Autowired
	private MessageUtil messageUtil;

	@Override
	public boolean supports(Class<?> clazz) {
		return Role.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "message.required.role.code", "Code required!");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "message.required.role.name", "Name required!");
	}

	public void methodAddValidate(Object target, Errors errors) {
		validate(target, errors);
		Role role = (Role) target;
		List<Role> roleList = roleService.findRoleByCode(role.getCode());
		if (roleList.size() > 0) {
			errors.rejectValue("code", "message.unique.role.code", new Object[] { role.getCode() }, "编码不能重复！");
		}
	}

	public void methodModifyValidate(Object target, Errors errors) {
		validate(target, errors);
		Role role = (Role) target;
		List<Role> roleList = roleService.findRoleByCode(role.getCode());
		if (roleList.size() == 1 && roleList.get(0).getId().intValue() != role.getId().intValue()) {
			errors.rejectValue("code", "message.unique.role.code", new Object[] { role.getCode() }, "编码不能重复！");
		}
	}

	public List<String> getErrors(BindingResult result) {
		List<String> errors = new ArrayList<String>();
		for (ObjectError error : result.getAllErrors()) {
			errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
		}
		return errors;
	}
}
